﻿using System.Collections.Generic;
using System.Collections.Immutable;
//using JetBrains.Annotations;


namespace Permission.Abstract;


/// <summary>
/// 权限组定义
/// </summary>
public class PermissionGroupDefinition
{
    /// <summary>
    /// 权限组唯一名
    /// </summary>
    public string Name { get; }

    public string DisplayName { get; set; }


    public IReadOnlyList<PermissionDefinition> Permissions => _permissions.ToImmutableList();
    private readonly List<PermissionDefinition> _permissions;


    public Dictionary<string, object> Properties { get; }

    public object this[string name]
    {
        get => Properties.FirstOrDefault(c => c.Key == name);
        set => Properties[name] = value;
    }

    public PermissionGroupDefinition(string name, string displayName = "")
    {
        Name = name;
        DisplayName = displayName ?? "";
        Properties = new Dictionary<string, object>();
        _permissions = new List<PermissionDefinition>();
    }

    public virtual PermissionDefinition AddPermission(string name, string displayName = "")
    {
        var permission = new PermissionDefinition(name, displayName);
        _permissions.Add(permission);
        return permission;
    }

    public virtual List<PermissionDefinition> GetPermissionsWithChildren()
    {
        var permissions = new List<PermissionDefinition>();

        foreach (var permission in _permissions)
        {
            AddPermissionToListRecursively(permissions, permission);
        }

        return permissions;
    }

    private void AddPermissionToListRecursively(List<PermissionDefinition> permissions, PermissionDefinition permission)
    {
        permissions.Add(permission);

        foreach (var child in permission.Children)
        {
            AddPermissionToListRecursively(permissions, child);
        }
    }

    public PermissionDefinition GetPermissionOrNull(string name)
    {
        return GetPermissionOrNullRecursively(Permissions, name);
    }

    private PermissionDefinition GetPermissionOrNullRecursively(IReadOnlyList<PermissionDefinition> permissions, string name)
    {
        foreach (var permission in permissions)
        {
            if (permission.Name == name) return permission;

            var childPermission = GetPermissionOrNullRecursively(permission.Children, name);
            if (childPermission != null)
            {
                return childPermission;
            }
        }
        return null;
    }
}
